<template>
  <div class="theQueryForm">
    <el-form
      v-if="option.length > 0"
      ref="theQueryFormRef"
      :model="form"
      inline
    >
      <el-form-item
        v-for="(item, index) in option"
        :key="index"
        :label="option[index].label"
        :prop="item.field"
      >
        <!-- checkbox多选框组 -->
        <div v-if="item.type == 'CheckBox'">
          <span
            @click="checkBoxChange(li, item)"
            v-for="(li, ind) in item.options"
            :key="'checkbox' + ind"
          >
            <i
              class="el-icon-check"
              :class="checkBox === li.value ? 'active' : 'noActive'"
            ></i>
            {{ li["label"] }}
          </span>
        </div>

        <!-- inputNumber 输入框 -->
        <el-input-number
          v-if="item.type === 'InputNumber'"
          v-model="form[item.field]"
          :controls="false"
          :step="1"
          :placeholder="item.placeholder || '请输入' + item.txt"
          :disabled="item.disabled"
          clearable
        ></el-input-number>
        <!-- input输入框 -->
        <el-input
          v-if="item.type === 'Input'"
          v-model="form[item.field]"
          :placeholder="item.placeholder || '请输入' + item.txt"
          :disabled="item.disabled"
          :maxlength="item.maxlength"
          @blur="(e)=>onInputBlur(e,item.field)"
          clearable
        />
        <!-- select下拉框 -->
        <el-select
          v-else-if="item.type === 'Select'"
          v-model="form[item.field]"
          :placeholder="item.placeholder || '请输入' + item.txt"
          :disabled="item.disabled"
          :filterable="item.filterable"
          @change="
            (value) => {
              if (typeof item.onChange === 'function') {
                item.onChange(value);
              }
            }
          "
          clearable
        >
          <el-option
            v-for="(li, ind) in item.options"
            :key="'option' + ind"
            :label="li[item['optionsKey'] || 'label']"
            :value="li[item['optionsValue'] || 'value']"
          />
        </el-select>
        <!-- 日期选择器 -->
        <el-date-picker
          v-else-if="item.type === 'DatePicker'"
          v-model="form[item.field]"
          unlink-panels
          type="date"
          :placeholder="item.placeholder || '请选择日期'"
          :disabled="item.disabled"
        />
        <!-- 日期区间选择器 -->
        <el-date-picker
          v-else-if="item.type === 'DatePickerRange'"
          v-model="form[item.field]"
          :type="item.dateType || 'daterange'"
          :value-format="item.valueFormat || 'yyyy/MM/dd'"
          :unlink-panels="true"
          :format="item.format || 'yyyy/MM/dd'"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :pickerOptions="item.pickerOptions || {}"
          :disabled="item.disabled"
          clearable
        />
        <!-- 按钮 -->
        <el-button
          v-else-if="item.type === 'Button'"
          :type="item.buttonType || 'primary'"
          @click="item.func"
          >{{ item.placeholder }}</el-button
        >
        <!-- 复合型select输入框 -->
        <el-input
          class="input-with-select"
          v-else-if="item.type === 'inputSelect'"
          type="inputSelect"
          :placeholder="item.placeholder || '请输入' + item.txt"
          v-model="form[item.value]"
          @change="oninput"
        >
          <el-select
            v-model="form[item.field]"
            :style="item.style"
            :slot="item.slot"
            :placeholderSelect="item.placeholderSelect || '请选择'"
            @change="onchange"
          >
            <el-option
              v-for="(li, ind) in item.options"
              :key="'option' + ind"
              :label="li[item.optionsKey || 'label']"
              :value="li[item.optionsValue || 'value']"
            />
          </el-select>
        </el-input>
        <!-- Cascader 级联选择器 -->
        <el-cascader
          :style="{ width: item.width }"
          v-else-if="item.type === 'Cascader'"
          v-model="form[item.field]"
          :placeholder="item.placeholder || '请选择' + item.txt"
          :options="item.options"
          :props="item.props"
          :disabled="item.disabled"
          clearable
        ></el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit('theQueryFormRef')">{{
          okTxt
        }}</el-button>
        <el-button v-if="isClose" @click="onClose('theQueryFormRef')">{{
          closeTxt
        }}</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
export default {
  name: "TheQueryForm",
  props: {
    /**
     * @param {Array} option 目前仅支持 输入框：input ，下拉框：select， 日期区间选择器：daterange ，日期选择器：date 复合下拉框输入， 级联选择器：Cascader
     */

    option: {
      /**
       *  type: 类型,
          field: 字段,
          txt: 中文字段,
          placeholder: placeholder,
          required: 是否必填,
          rules: 校验方法,
          options: select 数据集合,
          optionsKey:select下拉框键名,
          optionsValue:select下拉框值,
          api: 异步接口方法,
          params: api接口参数,
          defaultValue: 默认值
          label:标签文本
          slot: 输入框内容位置插槽
          filterable: select 是否可以搜索
       */
      type: Array,
      default: () => [],
    },
    isClose: {
      type: Boolean,
      default: true,
    },
    closeTxt: {
      type: String,
      default: "重置",
    },
    okTxt: {
      type: String,
      default: "搜索",
    },
    queryForm: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: {},
      select: "",
      input: "",
      checkBox: "",
    };
  },
  created() {
    this.getOption(this.option);
  },
  mounted() {},
  methods: {
    onInputBlur(e,field){
      this.$set(this.form, field, e.target.value.replaceAll(' ',''));
    },
    setFormValue(options) {
      console.log(this.form);
      Object.keys(options).forEach((key) => {
        this.form[key] = options[key];
        this.$set(this.form, key, options[key]);
        console.log(this.form);
      });
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$emit("onSubmit", {
            // values: { ...this.form, ...this.queryForm },
            values: { ...this.form},

          });
        } else {
          // console.log("error submit!!");
          return false;
        }
      });
    },

    onClose(formName) {
      this.$refs[formName].resetFields();
      this.checkBox = "";
      this.$emit("onClear");
    },
    onchange(e) {
      this.$emit("key", e);
    },
    oninput(e) {
      this.$emit("value", e);
    },
    checkBoxChange(e, item) {
      if (this.checkBox === e.value) {
        this.checkBox = "";
        delete this.form[item.field];
      } else {
        this.checkBox = e.value;
        this.form[item.field] = this.checkBox;
      }
    },
    /**
     * @description 获取配置项目，存在api接口时，自动请求数据并添加至对应数据中
     * @param {Array[Object]} option 表单配置项
     * @returns {Array[Object]} 返回新配置项
     */
    async getOption(option) {
      for (let i = 0; i < option.length; i++) {
        const item = option[i];
        this.$set(this.form, option[i].field, undefined);

        if (
          Object.prototype.hasOwnProperty.call(item, "defaultValue") &&
          item.defaultValue !== ""
        ) {
          this.$set(this.form, option[i].field, option[i].defaultValue);
        }
        if (
          Object.prototype.hasOwnProperty.call(item, "api") &&
          item.api !== ""
        ) {
          const api = item.api;
          await api({ ...item.params }).then((res) => {
            console.log(res, "aaaaa");
            item.options = res.data;
          });
        }
      }
      this.$emit("load", { type: "success" });
    },
    getField(row) {
      let val = "";
      switch (row.type) {
        case "Input":
          val = "";
          break;
        case "Select":
          val = "";
          break;
        case "DatePickerRange":
          val = [];
          break;
        case "DatePicker":
          val = "";
          break;
        default:
          val = "";
          break;
      }
      return val;
    },
    setForm(value) {
      this.form = value;
      console.log(this.form, "123");
    },
  },
};
</script>
<style scoped lang="scss">
::v-deep .input-with-select .el-input-group__prepend {
  background-color: #fff;
}

::v-deep .el-form {
  .el-form-item {
    margin-right: 20px;
  }
}

::v-deep .el-icon-check {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  margin-right: 10px;
  padding: 2px;
  color: #fff;
  cursor: pointer;

  &.active {
    color: #fff;
    background-color: #1890ff;
  }
}
</style>
